package cn.slipi.admin.common.response.builder;

import cn.slipi.admin.common.response.JsonResponse;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author lee
 */
public class ResponseBuilder {

    public static ModelAndView build(Object object) {
        MappingJackson2JsonView view = new MappingJackson2JsonView();
        view.setExtractValueFromSingleKeyModel(true);
        ModelAndView mav = new ModelAndView(view);
        mav.addObject(object);
        return mav;
    }

    public static void build(Integer code, String msg, ServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = response.getWriter();
        JsonResponse<String> jsonResponse = new JsonResponse<>();
        jsonResponse.setCode(code);
        jsonResponse.setMsg(msg);
        String result = JSONObject.toJSONString(jsonResponse);
        out.println(result);
        out.flush();
        out.close();
    }
}
